<?php
/**
 * @package site
 */

/**
 * Class designed to product sitemap.xml
 */
class Sitemap {
	
	/**
	 * Output one item of sitemap
	 *
	 * @param string $loc
	 * @param string $priority
	 * @param string $changefreg
	 */
	private static function itemGeneral($loc, $priority, $changefreg) {
		echo "
	<url>
		<loc>$loc</loc>
		<priority>$priority</priority>
		<changefreq>$changefreg</changefreq>
	</url>";
	}
	
	/**
	 * Generate output for one offer - the main view.
	 *
	 * @param Offer $offer
	 */
	private static function item(Offer $offer) {
		if ($offer->seoUrl == null || $offer->seoUrl == "") {
			$loc = Common::addParamsToUrl(Constants::WEB_DEFAULTPAGE . "/?", 
					Constants::REQ_ACTION, Constants::REQ_ACTION_OFFER ,
					Constants::REQ_TYPE, $offer->id);
		} else {
			$loc = Constants::WEB_DEFAULTPAGE . $offer->seoUrl;
		}
		
		if ($offer->top) {
			$priority = "0." . rand(7, 8);
		} else {
			$priority = "0." . rand(4, 6);
		}
		
		$changefreg = "weekly";
		
		self::itemGeneral($loc, $priority, $changefreg);
	}
	
	/**
	 * Output some by hand defined pages like main page, contact page ...
	 * Apply higher priority...
	 */
	private static function defaultPages() {
		self::itemGeneral(Constants::WEB_DEFAULTPAGE, "1", "daily");
		self::itemGeneral(Common::addParamsToUrl(Constants::WEB_DEFAULTPAGE."/?", 
				Constants::REQ_ACTION, Constants::REQ_ACTION_ABOUT), "0.9", "monthly");
		self::itemGeneral(Common::addParamsToUrl(Constants::WEB_DEFAULTPAGE."/?", 
				Constants::REQ_ACTION, Constants::REQ_ACTION_CONTACT), "0.9", "monthly");
	}
	
	/**
	 * Process sitemap.xml
	 */
	public static function init() {
		$info = SiteContext::getSiteContext();
		$connector = $info->getDBConnector();
		
		$res = $connector->query("select * from offers where status = 'visible'");
		
		header("Content-Type: application/xml;charset=utf-8");
		header("Vary: Accept");

		echo '<?xml version="1.0" encoding="utf-8"?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
		
		self::defaultPages();
		
		while ($offer = Offer::mysqlFetch($res)) {
			self::item($offer);
		}
		echo '</urlset>';
	}
}
?>